package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketCategory;
import com.cskaoyan.market.db.domain.MarketGoods;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.WxGoodsService;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.WxGoodsCategoryVo;
import com.cskaoyan.market.vo.WxGoodsDetailVo;
import com.cskaoyan.market.vo.WxGoodsListVo;
import com.github.pagehelper.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/goods")
public class WxGoodsController {

    @Autowired
    WxGoodsService wxGoodsService;

    @Autowired
    SecurityManager securityManager;

    @GetMapping("list")
    public Object list(String keyword, Integer brandId, Integer categoryId, Integer page, Integer limit, String sort, String order) {
        WxGoodsListVo wxGoodsListVo = wxGoodsService.list(keyword, brandId, categoryId, page, limit, sort, order);
        List<MarketCategory> filterCategoryList = wxGoodsListVo.getFilterCategoryList();
        List<MarketGoods> list = wxGoodsListVo.getList();

        Map<String, Object> data = new HashMap<>();
        data.put("filterCategoryList", filterCategoryList);
        data.put("list", list);
        Page pageList = (Page) list;
        data.put("total", pageList.getTotal());
        data.put("page", pageList.getPageNum());
        data.put("limit", pageList.getPageSize());
        data.put("pages", pageList.getPages());
        return ResponseUtil.ok(data);
    }

    @GetMapping("category")
    public Object category(Integer id) {

        WxGoodsCategoryVo wxGoodsCategoryVo = wxGoodsService.category(id);
        return ResponseUtil.ok(wxGoodsCategoryVo);
    }

    @GetMapping("count")
    public Object count() {
        Long goodsCount = wxGoodsService.count();
        return ResponseUtil.ok(goodsCount);
    }

    @GetMapping("detail")
    public Object detail(Integer id) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        Integer userId = user.getId();
        WxGoodsDetailVo wxGoodsDetailVo = wxGoodsService.detail(id,userId);
        return ResponseUtil.ok(wxGoodsDetailVo);
    }

    @GetMapping("related")
    public Object related(Integer id) {
        List<MarketGoods> marketGoodsList = wxGoodsService.related(id);
        return ResponseUtil.okList(marketGoodsList);
    }
}
